<?php
namespace app\api\controller;

use think\Controller;
use app\common\model\Release as ReleaseModel;

class Release extends Controller
{
    /**
     * 获取发布列表
     * @param int $page 页码
     * @param int $limit 每页数量
     * @param int $user_id 用户ID
     * @return json
     */
    public function list()
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }

        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        $list = ReleaseModel::with(['category'])
            ->where('user_id', $user_id)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $count = ReleaseModel::where('user_id', $user_id)->count();

        return json([
            'code' => 1,
            'data' => [
                'list' => $list,
                'total' => $count,
                'last_page' => ceil($count / $limit)
            ]
        ]);
    }

    /**
     * 提交发布
     * @param string $title 标题
     * @param string $content 内容
     * @param int $category_id 分类ID
     * @return json
     */
    public function submit()
    {
        $user_id = session('user_id');
        if (!$user_id) {
            return json(['code' => 0, 'msg' => '请先登录']);
        }

        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '非法请求']);
        }

        $data = $this->request->post();
        $validate = validate('Release');
        if (!$validate->scene('submit')->check($data)) {
            return json(['code' => 0, 'msg' => $validate->getError()]);
        }

        $data['user_id'] = $user_id;
        $data['status'] = 0; // 待审核

        if (ReleaseModel::create($data)) {
            return json(['code' => 1, 'msg' => '提交成功，请等待审核']);
        }
        return json(['code' => 0, 'msg' => '提交失败']);
    }
} 